<?php
/* 
    Name：FastPHP
    CopyRight: Mr.Fu 2019SR0832915
*/
namespace app\extend\juhe;

/*
	聚合短信接口插件
*/
use \app\base\Common;

class Sms extends Common
{
	private $URI='http://v.juhe.cn/sms/send';
	private $Dtype='json';
	private $Key='';
	// private $SendCodeTimeInterval=0;
	
    public function _initialize()
    {
    	//执行父类的构造方法
    	parent::_initialize();
    	$this->key=$this->Config['juhesms_secretkey'];
    	// $this->SendCodeTimeInterval=$this->Config['SendCodeTimeInterval'];
    }
    /*
    	temp_id：模板ID
    	mobile：手机号
    	code:验证码
    */
	public function SendCode($temp_id,$mobile,$code)
	{
		$return['code']=0;
		$return['msg']='';
		
		// $lasttime=cache('SendCheckCode_Time_'.$mobile);
		// $Interval=time()-$this->SendCodeTimeInterval;
		// 
		// if(($lasttime-$Interval)>=0){
		// 	WLog('juhe_sms_log',serialize($mobile.'手机发送过于频繁('.$this->SendCodeTimeInterval.'秒)'));
		// 	$return['code']=1;
		// 	$return['msg']='请'.$this->SendCodeTimeInterval.'秒后再试';
		// 	return $return;
		// }
		
		$params = array(
		    'key'   	=> $this->key, 		//您申请的APPKEY
		    'mobile'    => $mobile, 		//接受短信的用户手机号码
		    'tpl_id'    => $temp_id, 		//您申请的短信模板ID，根据实际情况修改
		    'tpl_value' =>'#code#='.$code 	//您设置的模板变量，根据实际情况修改
		);
		
		$paramstring = http_build_query($params);
		$content = $this->SmsCurl($this->URI, $paramstring);
		$result = json_decode($content, true);
		WLog('juhe_sms_log',serialize($result));
		if ($result && $result['error_code']==0){
		   //发送成功后开始记录
				cache('SendCheckCode_Time_'.$mobile,time());
				$return['code']=0;
				$return['msg']='发送成功';
				return $return;
		}else{
				$return['code']=2;
				$return['msg']='系统错误';
				return $return;
		}
	}
	
	private function SmsCurl($url, $params = false, $ispost = 0)
	{
		$httpInfo = array();
		$ch = curl_init();

		curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
		curl_setopt($ch, CURLOPT_USERAGENT, 'JuheData');
		curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60);
		curl_setopt($ch, CURLOPT_TIMEOUT, 60);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
		if ($ispost) {
			curl_setopt($ch, CURLOPT_POST, true);
			curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
			curl_setopt($ch, CURLOPT_URL, $url);
		} else {
			if ($params) {
				curl_setopt($ch, CURLOPT_URL, $url.'?'.$params);
			} else {
				curl_setopt($ch, CURLOPT_URL, $url);
			}
		}
		$response = curl_exec($ch);
		if ($response === FALSE) {
			//echo "cURL Error: " . curl_error($ch);
			return false;
		}
		$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
		$httpInfo = array_merge($httpInfo, curl_getinfo($ch));
		curl_close($ch);
		return $response;
	}
	
}